package com.multithreading.chart1.deadlock;

/**
 * @author chenqb
 * @project_name: java-multithreading
 * @package_name: com.cqb.deadlock
 * @ClassName: DeadLockTest2
 * @description: 展示线程死锁状态
 * 死锁形成条件：1.资源互斥 2.构成请求并持有 3.资源不可剥夺 4.环路等待
 * 避免死锁需要破坏掉其中至少一个条件即可。但是目前只有请求并持有条件和环路等待条件可以破坏。
 * 另外使用资源申请的有序性可以破坏死锁。
 * Author by cqb, Date on 2020/7/7，7:08
 * PS: Not easy to write code, please indicate.
 */
public class DeadLockTest2 {
    private static Object resoureA=new Object();
    private static Object resoureB=new Object();

    public static void main(String[] args) {
        //1.用资源申请的有序性改变请求并持有条件打破死锁状态
        //创建线程A
        Thread threadA=new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resoureB){
                    System.out.println(Thread.currentThread()+"get ResourceA");
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread()+"waiting get ResourceB");
                    synchronized (resoureA){
                        System.out.println(Thread.currentThread()+"get ResourceB");
                    }
                }
                }
        });
        //创建线程B
        Thread threadB=new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resoureA){
                    //演示死锁状态
//                synchronized (resoureB){
                    System.out.println(Thread.currentThread()+"get ResourceB");
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread()+"waiting get ResourceA");
                    synchronized (resoureB){
                        //演示死锁状态
//                    synchronized (resoureA){
                    System.out.println(Thread.currentThread()+"get ResourceA");
                    }
                }
            }
        });

        //启动线程A
        threadA.start();
        //启动线程B
        threadB.start();

    }



}
